<?php declare(strict_types=1);

namespace App\Services\Count;


use App\Models\User;
use App\Services\PrintSqlService;
use App\Util\ListUtil;

class UserService
{

    public function getUserList(): array
    {
        $users = User::query()->select(["id", "pid", "name"])->get()->toArray();
        $userList = ListUtil::createListsNode($users);
        return $userList;
    }


    public function getUserTree()
    {
        $users = User::query()->select(["id", "pid", "name"])->get()->toArray();
        $userTree = ListUtil::createTreeNode($users);
        return $userTree;
    }

    //通过链表的形式，直接从内存中获取下级
    public function getSub(int $user_id): array
    {
        $userList = $this->getUserList();
        $userSub = ListUtil::getListsNode($userList, ["id" => $user_id]);
        $userSubArray = ListUtil::listsNodeToArray([$userSub]);
        return $userSubArray;
    }


    //递归sql向上查询判断当前的等级
    public function userPrev(int $user_id): array
    {
        $data = [];
        $user = User::query()->where(['id' => $user_id])->select('id', 'name', 'pid')->first();
        if (empty($user)) {
            return $data;
        }
        $data[] = $user->toArray();
        if ($user->pid > 0) {
            $tmp = $this->userPrev((int)$user->pid);
            $data = array_merge($data, $tmp);
        }
        return $data;
    }


    public function handleUserAccountRelation(int $user_id, array $arrs = []): array
    {
        if (empty($arrs)) {
            $arrs = $this->userPrev($user_id);
        }
        //把数组反转
        $arrs = array_reverse($arrs);
        //获取当前账号
        $oem_id = $agent1_id = $agent2_id = $agent3_id = $agent4_id = 0;
        $profit_column = "oem_profit";
        $fee_column = "oem_fee";
        foreach ($arrs as $k => $v) {
            if ($k == 0) {
                $oem_id = $v['id'];
                $profit_column = "oem_profit";
                $fee_column = "oem_fee";
            } else {
                $key = "agent" . $k . "_id";
                $$key = $v["id"];
                $profit_column = "agent" . $k . "_profit";
                $fee_column = "agent" . $k . "_fee";
            }
        }
        return [
            [$oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id],
            [$profit_column, $fee_column]
        ];
    }

}